
import React, { useState, useRef, useEffect } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Popconfirm } from 'antd';
import { useModel } from 'umi'; 
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { getRoleList, addRole, removeRole, updateRole, getDeptList } from '@/services/permissions/api';
import OptForm from './OptForm';
import { OptType } from '@/utils/constants';
import { MsgType, showMsg, isNull } from '@/utils/utils';
import BreadcrumbDept from '@/components/BreadcrumbDept';

const RoleList: React.FC = () => {
  const [visible, setVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<PERMISSIONSAPI.RoleListItem>({});
  const [optType, setOptType] = useState<string>(OptType.ADD);
  const actionRef = useRef<ActionType>();
  const [deptList, setDeptList] = useState([]);
  const { initialState } = useModel('@@initialState');
  const [clickRow, setClickRow] = useState(''); // 当前选中的行编号，用于定位颜色

  useEffect(() => {
    getDeptList({}).then(res => {
      setDeptList(res || [])
    }).catch(error => {
      showMsg(error?.data?.errmsg)
    })
  }, [])

  const title = () => {
    return <div>
      删除角色会导致已分配该角色账号无<br/>法使用，是否继续？
    </div>
  };

  const columns: ProColumns<PERMISSIONSAPI.RoleListItem>[] = [
    {
      title: '业务科室',
      dataIndex: 'dept_code',
      hideInTable: true,
      valueType: 'select',
      colSize: 2,
      formItemProps: { labelCol: { span: 4 }, wrapperCol: { span: 20 } },
      initialValue: initialState?.currentUser?.identity_type !== 'A' ? initialState?.currentUser?.dept_code : null,
      fieldProps: {
        options: deptList.map(item => {
          return {
            label: `${item.dept_code}-${item.dept_name}`,
            value: item.dept_code,
            data: item,
          }
        }),
        showSearch: true,
        filterOption: true,
        disabled: initialState?.currentUser?.identity_type !== 'A',
      }
    },
    {
      title: '所属业务科室',
      dataIndex: 'dept_name',
      hideInSearch: true,
    },
    {
      title: '角色名称',
      dataIndex: 'role_name'
    },
    {
      title: '角色描述',
      dataIndex: 'role_desc',
      search: false
    },
    {
      title: '分配账号数',
      dataIndex: 'oper_num',
      align: 'right',
      search: false
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      render: (_, record) => [
        <a key="edit"
          onClick={() => {
            setVisible(true);
            setCurrentRow(record);
            setOptType(OptType.EDIT);
          }}>编辑</a>,

        <Popconfirm
          placement="topRight"
          title={title}
          key="delete"
          onConfirm={() => handleRemove(record)}
          okText="确认删除"
          cancelText="再想想">
          <a>删除</a>
        </Popconfirm>,
        <a key="copy"
        onClick={() => {
          setVisible(true);
          setCurrentRow(record);
          setOptType(OptType.COPY);
        }}>复制</a>
      ]
    }
  ];

  /**
   * 删除角色
   * @param selectedRow 
   * @returns 
   */
  const handleRemove = async (selectedRow: PERMISSIONSAPI.RoleListItem) => {
    if (!selectedRow) return;
    try {
      await removeRole(selectedRow.role_id);
      showMsg('已删除', MsgType.SUCCESS);
      if (actionRef.current) {
        actionRef.current.reload();
      }
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  };

  /**
   * 添加，修复角色
   * @param fields 
   */
  const handleAdd = async (fields: PERMISSIONSAPI.RoleListItem) => {
    try {
      if (optType === OptType.ADD || optType === OptType.COPY) {
        await addRole({ ...fields });
      } else {
        await updateRole({ ...fields });
      }
      showMsg('已保存', MsgType.SUCCESS);
      if (actionRef.current) {
        actionRef.current.reload();
      }
      return true;
    } catch (error) {
      showMsg(error?.data?.errmsg);
      return false
    }
  };

  return (
    <PageContainer extra={[
      <BreadcrumbDept />
     ]} breadcrumb={{}}>
      <ProTable<PERMISSIONSAPI.RoleListItem, COMMON.PageParams & PERMISSIONSAPI.RoleListItem>
        actionRef={actionRef}
        rowKey="role_id"
        bordered
        search={{
          span: 6,
          optionRender: (searchConfig, formProps, dom) => {
            dom.shift();
            return [...dom];
          }
        }}

        request={async (params) => {
          try {
            const data: PERMISSIONSAPI.RoleList = await getRoleList(params);
            return {
              data: data.record_list,
              success: true,
              total: data.sum_record_num
            };
          } catch (error) {
            showMsg(error?.data?.errmsg);
            return {
              data: [],
              success: true,
              total: 0
            };
          }
        }}
        columns={columns}
        options={false}
        pagination={{
          showQuickJumper: true
        }}
        toolbar={{
          menu: {
            type: 'inline',
            items: [
              {
                key: 'add',
                label: <Button 
                onClick={() => {
                  setVisible(true);
                  setCurrentRow({});
                  setOptType(OptType.ADD);
                }} 
                icon={<PlusOutlined />} 
                type="primary">
                新建
              </Button>
              }
            ]
          }
        }}
        onRow={record => {
          return {
            onClick: event => { setClickRow(record.role_id) }, // 点击行
            onMouseEnter: event => {}, // 鼠标移入行
            onMouseLeave: event => {},
          };
        }}
        rowClassName={(record) => {
          return record.role_id === clickRow ? 'tableRowClick' : ''
        }}
      />
      
      {visible && <OptForm
        record={currentRow}
        handleVisible={setVisible}
        handleAdd={handleAdd}
        optType={optType}
        deptList={deptList}
      />}
    </PageContainer>
  );
};

export default RoleList;
